'use client';
import { useState, useEffect } from 'react';
import { ProChat } from '@ant-design/pro-chat';
import { useTheme } from 'antd-style';
import { Card, Row, Col } from 'antd';
import RPAButton from './Button';
import RPAEcharts from './RPAEcharts';

export default function Vanna() {

  const theme = useTheme();

  const [showComponent, setShowComponent] = useState(false);

  const [cardWidth, setCardWidth] = useState(650);

  useEffect(() => setShowComponent(true), []);

  useEffect(() => {
    setShowComponent(true);

    // 定义一个函数来动态设置卡片宽度
    const updateCardWidth = () => {
      const windowWidth = window.innerWidth;
      setCardWidth(windowWidth - 200); // 设置为窗口宽度的 1/3
    };

    // 页面加载时和窗口大小改变时更新宽度
    updateCardWidth();
    window.addEventListener('resize', updateCardWidth);

    // 清理事件监听
    return () => {
      window.removeEventListener('resize', updateCardWidth);
    };
  }, []);

  // 判断值是否为JSON数据
  const isJSON = (str: string): boolean => {
    try {
      const parsed = JSON.parse(str);
      return typeof parsed === 'object' && parsed !== null;
    }catch(error){
      return false;
    }
  }

  // 通过网络请求接口，获取当前的用户的名称
  const getUserName = (jobId: string): string => {
    return jobId;
  }

  return (
    <Row style={{backgroundColor: theme.colorBgLayout}}>
      <Col xl={{span: 16, offset: 4}} md={{span: 24}}>
    <div
      style={{
        height: '100vh', // 确保父容器的高度也是100vh
        display: 'flex', // 使用Flexbox布局
        flexDirection: 'column', // 子元素垂直排列
        minWidth: '500px'
      }}
    >
      {
        showComponent && <ProChat
          showTitle
          helloMessage = {<><br />Hi 👋, 我是RPA Chat!<br /><br />很高兴遇见你！🤗 你可以向我提出想要的数据信息，📈 以便为你查询。<br /><br /></>}
          style={{
            flexGrow: 1, // 让ProChat占据剩余空间
            width: '100%',
          }}
          userMeta={{
            avatar: 'http://localhost:82/user01.svg',
            title: getUserName('UserName??')
          }}
          assistantMeta={{
            avatar: 'http://localhost:82/logo01.svg',
            title: 'RPA Chat'
          }}
          chatItemRenderConfig={{
            
            actionsRender : (props) => {
              if(props?.originData?.role === 'assistant' && isJSON(props?.originData?.content)){
                return(
                  <></>
                  //<RPADownload {...props} />
                )
              }
            },

            contentRender(item: Record<string, any>, defaultDom: React.ReactNode) {
                if(item?.originData?.role === 'assistant' && isJSON(item?.originData?.content))
                {
                    const str = (item?.originData?.content).toString();
                    console.log(str)
                    return <Card style={{ maxWidth: `${cardWidth}px`, minWidth: '650px' }}><RPAEcharts content={str} /></Card>
                }
                return defaultDom;
            },
          }}
          actions={{ // 自定义
              render: (defaultDoms) => {
                return [
                  <RPAButton />,
                  ...defaultDoms,
                ];
              },
              flexConfig: {
                gap: 24,
                direction: 'horizontal',
                justify: 'space-between',
              },
          }}
          request={
            async (messages) => {
              const lastMessage = messages[messages.length - 1];
              const content = lastMessage.content?.toString() || "";
              const formData = new FormData();
              formData.append('message', content);

              const response = await fetch('/api/qwen', {
                method: 'POST',
                body: formData
              });

              const data = await response.json();

              // 检查返回的内容是否为 JSON
              const responseContent = data['content'];

              return responseContent;
            }
          }
        />
      }
    </div>
    </Col>
    </Row>
  );
}